import { View, Image, Text } from '@tarojs/components'
import { useState, useEffect, useLayoutEffect, useCallback } from 'react'
import Taro from '@tarojs/taro'
import { HttpGet, HttpDelete } from '@/network/servers'
import dayjs from 'dayjs'
import Utils from '@/utils/index'
import { connect } from 'react-redux'
import { getBrowserController, getNet, getStorage, getWxSDKParams } from '@/pages/components/utils';
import { LgPopLayer, LgEmpty } from "lancoo-ui-mobile";
import '../../../images/public/style.css'
import './index.scss'
import { create } from 'lodash'
import Loading from '../../component/load'
import { getLunar } from 'chinese-lunar-calendar'
const storage = getStorage()
var wx = require('weixin-js-sdk')
const {
  getQueryVariable,
  getDateGap,
} = Utils


const requireContext = require.context('../../../images/fileIcon', true, /^\.\/.*\.svg$/);
const svgs = requireContext.keys().map(requireContext);
const keys = requireContext.keys()
let fileObj = {}

keys.map((item, index) => {
  let str = item.replace('./', '').replace('.svg', '')
  fileObj[str] = svgs[index]
})


function App(props) {
  console.log(props, 'props');

  let {
    userInfo,
    baseUrl,
    timeType,
    currentDate,
    scheduleList,

  } = props

  const getToken = () => {
    if (getQueryVariable('env') === 'weapp') {
      return getQueryVariable('lg_tk')
    } else {
      return storage.get('token') || getQueryVariable('lg_tk')
    }
  }
  const [weekList, setWeekList] = useState(['一', '二', '三', '四', '五', '六', '日']);
  const [typeScheduleList, setTypeScheduleList] = useState([]);
  const [dayScheduleList, setDayScheduleList] = useState([]);
  const [itemTime, setItemTime] = useState('');

  const [isOpen, setIsOpen] = useState(false);

  const handleLayer = useCallback((item = null) => {
    if (item) {
      setItemTime(item?.date)
      let itemList = item?.list || []
      setDayScheduleList(itemList);
      // setIsOpen(itemList.length > 0 ? true : false);
    }
    setIsOpen(!isOpen);
  }, [isOpen]);
  useLayoutEffect(() => {   //把获取到的日程列表按日期整合进表格中
    if (!currentDate) {
      return;
    }
    let year = dayjs(currentDate).get('year');
    let month = dayjs(currentDate).get('month') + 1;
    let day = dayjs().get('date');
    let startWeek = new Date(year, month - 1, 1).getDay();
    let maxDay = new Date(year, month, 0).getDate();
    let arr: any = [];
    for (let i = 1; i <= maxDay; i++) {
      arr.push({
        day: i,
        dayText: i,
        date: year + '-' + month + '-' + i,
        week: dayjs(year + '-' + month + '-' + i).get('day'),
        list: []
      });
    }
    if (startWeek !== 1) {
      for (let i = 0; i < startWeek - 1; i++) {
        arr.unshift({});
      }
    }
    let existList = [];
    arr.forEach((item) => {
      // console.log(holidayList, 'holidayList')
      // let obj = holidayList.filter(child => dayjs(item.date).format('YYYY-MM-DD') === dayjs(child.date).format('YYYY-MM-DD'))[0];
      // if (obj) {
      //   if (!existList.includes(obj.holidayName)) {
      //     item.holidayName = obj.holidayName;
      //   }
      //   item.isHoliday = true;
      //   existList.push(obj.holidayName);
      // }
      scheduleList.forEach((child) => {
        if (item.date && dayjs(child.scheduleDate).format('YYYY-MM-DD') === dayjs(item.date).format('YYYY-MM-DD')) {
          item.list.push(child);
        }
      })
    })
    setTypeScheduleList(arr);
  }, [scheduleList, currentDate]);

  const getLunarDate = (dateStr) => {
    const lunarDate = dayjs(dateStr); // 转换为农历日期

    const lunarDay = lunarDate.date(); // 获取农历的天数
    const lunarMonth = lunarDate.month() + 1; // 获取农历的月份

    // 格式化农历日期
    const lunarDayStr = ["", "初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十"];

    return `${lunarDayStr[lunarDay]}`;
  }

  // 跳转发布页面
  const goCreate = () => {
    let url = '/pages/scheduleApp/createSchedule/index?id=&signin=1&date=' + (itemTime);
    Taro.navigateTo({
      url
    })
  }
  //跳转详情页
  const goDetail = (data) => {
    console.log(data, 'data11');
    let url = '';
    // if (data.beCourse == 1) return;
    if (data.isCreate === 1) {
      let start = data.startTime1
      let end = data.endTime1
      url = '/pages/scheduleApp/createSchedule/index?startDate=' + currentDate + '&start=' + start + '&end=' + end
    } else {
      if (data.beCourse == 1) {
        url = '/pages/scheduleApp/courseDetail/index?beCourse=' + data.beCourse + '&class=' + (data.class ? data.class : '无') + '&title=' + data.scheduleContent + '&address=' + (data.scheduleLocation ? data.scheduleLocation : '无')
          + '&scheduleDate=' + data.scheduleDate + '&startTime=' + data.startTime1 + '&endTime=' + data.endTime1 + '&times=' + data.times
      } else {
        url = '/pages/scheduleApp/scheduleDetail/index?id=' + data.scheduleId
      }
    }
    Taro.navigateTo({
      url
    })
  }

  const getNumberHZ = (date) => {
    if (!date) {
      return;
    }
    let year = dayjs(date).get("year");
    let month = dayjs(date).get("month") + 1;
    let day = dayjs(date).get("date");
    let dateInfo = getLunar(year, month, day);
    let result = dateInfo.dateStr;
    if (result.indexOf("初一") > -1) {
      result = result.replace("初一", "");
    } else {
      result = result.split("月")[1];
    }
    return result;
  }

  return (
    <View className='type_month_container'>
      <View className='week_list'>
        {
          weekList.map((item, index) => (
            <View className='week_one' key={index}>
              {item}
            </View>
          ))
        }
      </View>
      <View className='schedule_table'>
        {
          typeScheduleList.map((item, index) => {
            // console.log(item,'fghjkl',item?.holidayName,'item?.holidayName',item?.date);

            return (
              <View onClick={() => handleLayer(item)} style={{ borderBottom: index > 27 ? 'none' : '' }} className={`schedule_one ${item?.isHoliday || [6, 0].includes(item?.week) ? 'relax' : ''}`} key={index}>
                {/* <View className={'schedule_day' + ((item?.date && dayjs(item?.date).format('YYYY-MM-DD')) == currentDate ? ' is_current_day' : '')}> */}
                <View className={'schedule_day' + ((item?.date && dayjs(item?.date).format('YYYY-MM-DD')) == dayjs().format('YYYY-MM-DD') ? ' is_current_day' : '')}>
                  <View className='schedule_day_time'>
                    {item?.day || ''}
                  </View>
                  <View className='day_text'>{getNumberHZ(item?.date) || ''}</View>
                </View>
                {
                  Array.isArray(item?.list) && item?.list.length < 4 ?
                    item?.list.map((itm, idx) => {
                      return (
                        <View className='schedule_item'><View className='item_icon'></View>{itm?.scheduleTitle}</View>
                      )
                    })
                    :
                    Array.isArray(item?.list) && item?.list.length > 3 ?
                      <View className='schedule_item schedule_item_num'>{Array.isArray(item?.list) && item?.list?.length}个日程</View>
                      : ''
                }
              </View>
            )
          })
        }
      </View>
      <LgPopLayer
        position="bottom"
        isOpen={isOpen}
        showLayer={handleLayer}
        showClose
        title={<Text>{itemTime}<Text className='item_num'>（共<Text style={{ color: '#333' }}>{dayScheduleList && dayScheduleList.length}</Text>个日程）</Text></Text>}
        // customTitle={<Text>sadas</Text>}
        // customTitleClass='item_num'
        className='time_list_popLayer'
        titleContainerClass='time_list_popLayer_title'
        titleClass='popLayer_title'
        closeIconClass='popLayer_icon'
        insideContentClass='popLayer_Content'
        customContentClass='popLayer_customContent'
      >
        <View className="schedule_list_view">
          <View className='create_schedule' onClick={() => goCreate()}>添加</View>
          {
            dayScheduleList.length > 0 ?
              dayScheduleList.map((item, index) => {
                return (
                  // <View className='list_item' onClick={() => checkTime(index)}>
                  <View className='list_item' >
                    <View className='item_index'>{index + 1}</View>
                    <View className='item_info'>
                      <View className='item_name'>{item?.scheduleTitle}</View>
                      <View className='item_info_address'>
                        <View className='time_view'>{item?.startTime + '-' + item?.endTime}</View>
                        <View>{item?.scheduleLocation}</View>
                      </View>
                    </View>
                    <View className='item_go_icon' onClick={() => goDetail(item)}></View>
                  </View>
                )
              })
              :
              <LgEmpty type='data' size='large'>
                暂无日程
              </LgEmpty>
          }
        </View>
      </LgPopLayer>
    </View>
  )
}

const mainProps = ({ commonData }) => {
  return {
    userInfo: commonData.userInfo,
    env: commonData.env,
    noticeAddr: commonData.noticeAddr,
    baseUrl: commonData.baseUrl
  }
}

export default connect(mainProps)(App);
